<template>
  <el-col class="app-v-center app-column" style="overflow-y: auto;">
    <el-row class="app-h-48px px-0 app-fill-width app-v-center px-4 app-bb-1px-l2" style="background: #dfe9f5" :gutter="10">
      <div class="app-flex-1">
        <el-button
          size="mini"
          @click="$router.back()"
        >返回</el-button>
      </div>
      <el-button
        v-if="role < 3"
        size="mini"
        @click="toAddDispatch"
      >新增发货单</el-button>
    </el-row>
    <el-table
      :data="dispatchList"
      class="app-flex-1"
      style="width: 100%;overflow-y: auto;"
    >
      <!-- <el-table-column
        type="selection"
        width="55"
      /> -->
      <el-table-column
        prop="name"
        align="center"
        label="奖品名称"
        width="150"
      />
      <el-table-column
        prop="consigneeMobile"
        align="center"
        label="收货电话"
        width="120"
      />
      <el-table-column
        prop="address"
        align="center"
        label="收货地址"
      />
      <el-table-column
        prop="consigneeName"
        align="center"
        label="收货人姓名"
      />
      <el-table-column
        prop="count"
        align="center"
        label="奖品数量
"
      />
      <!-- <el-table-column
        prop="isBuy"
        align="center"
        label="使用赞助"
      >
        <template slot-scope="scope">
          {{ scope.row.isBy === 0 ? '否': '是' }}
        </template>
      </el-table-column> -->
      <!-- <el-table-column
        prop="state"
        align="center"
        label="物流状态"
      >
        <template slot-scope="scope">
          {{ scope.row.isBy === 0 ? '未送达': '已送达' }}
        </template>
      </el-table-column> -->
      <!-- <el-table-column
        prop="status"
        align="center"
        label="活动会长收到"
      >
        <template slot-scope="scope">
          {{ scope.row.isBy === 0 ? '未收到': '收到' }}
        </template>
      </el-table-column> -->
      <el-table-column
        prop="logisticsCompany"
        align="center"
        label="物流公司"
      />
      <el-table-column
        prop="logisticsNumber"
        align="center"
        label="物流编号"
      />
      <el-table-column
        prop="prizeCost"
        align="center"
        label="奖品成本"
      />
      <el-table-column
        align="center"
        width="250"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="toViewDetail(scope.$index, scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)"
          >编辑</el-button>
          <el-button
            v-if="role<3"
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="mb-10 mt-5"
      background
      :current-page.sync="pageNo"
      :page-sizes="[10, 20, 50]"
      :page-size.sync="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="getDispatchs"
      @current-change="getDispatchs"
    />
    <el-dialog
      :title="isEdit? '编辑发货单' : '新增发货单'"
      :visible.sync="addDispatchDialog"
      width="50vw"
      custom-class="app-height-70vh app-scroll-y"
      @close="cancelViewDetail"
    >
      <el-form ref="form" class="app-width-90p" :rules="rules" :model="form" label-width="160px">
        <el-form-item prop="eventPrizeId" label="奖品">
          <el-select v-model="form.eventPrizeId" :disabled="viewDetail || role===3">
            <el-option
              v-for="item in awardList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="count" label="奖品数量">
          <el-input v-model.number="form.count" :disabled="viewDetail || role===3" type="number" />
        </el-form-item>
        <!-- <el-form-item prop="prizeCost" label="奖品成本">
          <el-input v-model.number="form.prizeCost" :disabled="viewDetail || role===3" type="number" />
        </el-form-item> -->
        <el-form-item prop="consigneeName" label="收货人姓名">
          <el-input v-model="form.consigneeName" :disabled="viewDetail || role===3" />
        </el-form-item>
        <el-form-item prop="consigneeMobile" label="收货人电话">
          <el-input v-model="form.consigneeMobile" :disabled="viewDetail || role===3" />
        </el-form-item>
        <el-form-item prop="logisticsNumber" label="物流编号">
          <el-input v-model="form.logisticsNumber" :disabled="viewDetail" @input="getDeliver()" />
        </el-form-item>
        <el-form-item prop="logisticsCompany" label="物流公司">
          <el-input v-model="form.logisticsCompany" :disabled="viewDetail" />
        </el-form-item>
        <!-- <el-form-item prop="state" label="物流状态">
          <el-select v-model="form.state" :disabled="viewDetail || role===3" placeholder="">
            <el-option label="已送达" :value="1" />
            <el-option label="未送达" :value="0" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="收货地址">
          <el-cascader v-model="selectAdress" :disabled="viewDetail || role===3" :options="map" :props="{value: 'name',label: 'name'}" />
        </el-form-item>
        <el-form-item prop="address" label="详细地址">
          <div class="app-flex">
            <el-input v-model="form.address" :disabled="viewDetail || role===3" />
            <el-button
              class="ml-4"
              size="mini"
              type="primary"
              plain
              :disabled="viewDetail || role===3"
              @click="changeAdress"
            >识别</el-button>
            <el-button
              class="ml-4"
              size="mini"
              type="primary"
              plain
              :disabled="viewDetail || role===3"
              @click="copyLink"
            >一键复制</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addDispatchDialog = false">取 消</el-button>
        <el-button type="primary" @click="addDispatch">确 定</el-button>
      </div>
    </el-dialog>
  </el-col>
</template>

<script>
import { getMapJSON,updateDispatch,deleteDispatch,addDispatch,getDispatchs,parseAdress,getDeliver } from '@/api/dispatch'
import { getAwards } from '@/api/award'
export default {
  data: () => ({
    // 表单验证规则
    rules: {
      eventPrizeId: [
        { required: true, message: '请选择奖品', trigger: 'blur' }
      ],
      consigneeMobile: [
        { required: true, message: '请输入收件人手机号', trigger: 'blur' }
      ],
      consigneeName: [
        { required: true, message: '请输入收件人姓名', trigger: 'blur' }
      ],
      count: [
        { required: true, message: '请输入奖品数量', trigger: 'blur' }
      ],
      // isBuy: [
      //   { required: true, message: '请选择是否使用赞助费购买', trigger: 'blur' }
      // ],
      logisticsCompany: [
        { required: true, message: '请输入物流公司', trigger: 'blur' }
      ],
      // logisticsNumber: [
      //   { required: true, message: '请填写物流编号', trigger: 'blur' }
      // ],
      address: [
        { required: true, message: '请填写详细地址', trigger: 'blur' }
      ]
      // prizeCost: [
      //   { required: true, message: '请输入奖品成本', trigger: 'blur' }
      // ],
      // state: [
      //   { required: true, message: '请选择物流状态', trigger: 'blur' }
      // ]
      // status: [
      //   { required: true, message: '请选择活动会长是否收到', trigger: 'blur' }
      // ]
    },
    isEdit: false,
    viewDetail: false,
    role: Number(JSON.parse(localStorage.getItem('userInfo')).role),
    addDispatchDialog: false,
    dispatchList: [],
    pageNo: 1,
    pageSize: 10,
    total: 0,
    map: [],
    selectAdress: [],
    awardList: [],
    form: {
      address: null,
      consigneeMobile: '',
      consigneeName: '',
      count: null,
      // isBuy: null,
      logisticsCompany: '',
      logisticsNumber: '',
      eventPrizeId: '',
      prizeCost: null,
      state: null
      // status: null
    }
  }),
  mounted() {
    getMapJSON().then(res => {
      if (res.code === 200) {
        this.map = JSON.parse(res.data)
      }
    })
    this.getAwards()
    this.getDispatchs()
  },
  methods: {
    copyLink() {
      const str = `${this.form.consigneeName} ${this.form.consigneeMobile} ${this.form.address}`
      navigator.clipboard.writeText(str).then(() => {
        this.$message({ type: 'success',message: '复制成功' })
      })
    },
    // 物流状态
    getDeliver() {
      getDeliver({ no: this.form.logisticsNumber }).then(res => {
        this.form.logisticsCompany = res.data[0].name
      })
    },
    // 奖品信息用于选择
    getAwards() {
      const params = {
        pageNo: this.pageNo,
        pageSize: 100
      }
      getAwards(params).then(res => {
        if (res.code === 200) {
          this.awardList = res.data.dataList
          this.total = res.data.total
        }
      })
    },
    //
    getDispatchs() {
      const params = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        activeId: Number(this.$route.query.id)
      }
      getDispatchs(params).then(res => {
        if (res.code === 200) {
          this.dispatchList = res.data.dataList
          this.total = res.data.total
        }
      })
    },
    toAddDispatch() {
      this.selectAdress = []
      this.form = {
        activeId: Number(this.$route.query.id),
        address: '',
        consigneeMobile: '',
        consigneeName: '',
        count: null,
        // isBuy: null,
        province: '',
        city: '',
        county: '',
        logisticsCompany: '',
        logisticsNumber: '',
        name: '',
        prizeCost: null,
        state: null
        // status: null
      }
      this.isEdit = false
      this.addDispatchDialog = true
    },
    toViewDetail(index,row) {
      this.viewDetail = true
      this.form = row
      this.selectAdress = []
      const { province,city,county } = row
      if (province && city && county) {
        this.selectAdress = [province,city,county]
      }
      // this.$refs.form.validate((v) => {})
      this.addDispatchDialog = true
    },
    cancelViewDetail() {
      this.viewDetail = false
      this.addDispatchDialog = false
    },
    changeAdress() {
      // 省市区未选全解析详细地址
      parseAdress({ address: this.form.address }).then(res => {
        const { province,city,county,phonenum } = res.data
        this.form = {
          ...this.form,
          province,city,county
        }
        if (province && city && county) {
          // 有结果
          this.selectAdress = [province,city,county]
        }
        if (phonenum) {
          this.form.consigneeMobile = phonenum
        }
      })
      // if (this.selectAdress.length < 3) {
      // }
    },
    handleEdit(index,row) {
      this.isEdit = true
      this.form = row
      this.selectAdress = []
      const { province,city,county } = row
      if (province && city && county) {
        this.selectAdress = [province,city,county]
      }
      this.addDispatchDialog = true
      this.changeAdress()
      // 对地址进行解析
      // if (this.detailAdress.includes('省') || this.detailAdress.includes('市')) {
      //   // 详细地址存在、省、市、区不拼第二次
      //   this.form.address = this.detailAdress
      // } else {
      // if (this.form.address instanceof Array) {
      //   this.form.address = this.form.address.join('') + this.detailAdress
      // }
      // }
    },
    handleDelete(index,row) {
      this.$confirm(`确认删除货单${row.name}？`,'提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDispatch({ id: row.id }).then(res => {
          if (res.code === 200) {
            this.$message('删除成功')
            this.pageNo = 1
            this.getDispatchs()
          }
        })
      }).catch(() => {
        this.$message('已取消')
      })
    },
    addDispatch() {
      if (this.viewDetail) {
        this.addDispatchDialog = false
        return
      }
      this.$refs.form.validate(valid => {
        if (this.selectAdress.length < 3) {
          this.$message({ type: 'warning',message: '请选择地址' })
        }
        if (valid) {
          if (!this.form.address || this.form.address.length < 3) {
            this.$message({ type: 'warning',message: '请选择地址' })
            return
          }
          // if (!this.form.address) {
          //   this.$message({ type: 'warning',message: '请填写详细地址' })
          //   return
          // }
          // this.form.address = this.form.address.join('').concat(this.detailAdress)
          if (this.isEdit) {
            updateDispatch(this.form).then(res => {
              if (res.code === 200) {
                this.$message({ type: 'success',message: '操作成功' })
                this.addDispatchDialog = false
                this.getDispatchs()
              }
            })
          } else {
            addDispatch(this.form).then(res => {
              if (res.code === 200) {
                this.$message({ type: 'success',message: '操作成功' })
                this.addDispatchDialog = false
                this.pageNo = 1
                this.getDispatchs()
              }
            })
          }
        }
      })
    },
    // 拿到地址
    getTown(e) {
      this.address = e
    }
  }
}
</script>
